package com.bs.service;

import com.bs.service.util.FtpUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.Yaml;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by wenguangjia on 2017/6/1.
 */
@Service
public class ActionConfigService {

    @Value("${actionConfig.localPath}")
    private String localPath;
    @Value("${actionConfig.fileName}")
    private String fileName;

    @Value("${actionConfig.server.location}")
    private String[] locations;
    @Value("${actionConfig.server.ip}")
    private String[] ips;
    @Value("${actionConfig.server.port}")
    private int[] port;
    @Value("${actionConfig.server.username}")
    private String[] username;
    @Value("${actionConfig.server.password}")
    private String[] password;
    @Value("${actionConfig.server.serverPath}")
    private String serverPath;


    public Map query(String location) {
        location=location.toLowerCase();
        Map map = null;
        try {
            File dumpFile = new File(localPath + location+fileName);
            if(!dumpFile.exists()){
                boolean flag=false;
                for (int i = 0; i < locations.length; i++) {
                    if(location.equals(locations[i])){
                        flag = FtpUtil.download(ips[i], port[i], username[i], password[i], serverPath, localPath, fileName,location+fileName);
                    }
                    if (!flag) {
                        return null;
                    }
                }

            }
            Yaml yaml = new Yaml();
            map = (HashMap) yaml.load(new FileInputStream(dumpFile));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            return map;
        }
    }

    public void save(String location,Map map) throws FileNotFoundException {
        try {
            location=location.toLowerCase();
            Yaml yaml = new Yaml();
            yaml.dump(map, new FileWriter(localPath + location+fileName));
            for (int i = 0; i < locations.length; i++) {
                if (location.equals(locations[i])) {
                    FtpUtil.upload(ips[i], port[i], username[i], password[i], serverPath, localPath, fileName, location + fileName);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
